import Base from 'antd/es/typography/Base'
import axios from 'axios'
import { message } from 'antd'
const instance = axios.create({
  baseURL: import.meta.env.VITE_URL,
  timeout: 3000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    Authorization: `Bearer ${localStorage.getItem('token')}`
  }
})

instance.interceptors.request.use(
  (config: any) => {
    return config
  },
  (err: string) => {
    return Promise.reject(err)
  }
)
instance.interceptors.response.use(
  (res: any) => {
    const { code, data, msg } = res.data
    if (code === 200) {
      return data
    } else {
      message.error('请求失败')
      return Promise.reject(new Error(msg))
    }
  },
  err => {
    //处理网络错误
    let msg = ''
    const status = err.response.status
    switch (status) {
      case 401:
        msg = 'token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      default:
        msg = '无网络'
    }

    message.error(msg)

    return Promise.reject(err)
  }
)
// 测试
export default {
  get<T>(url: string, params: object): Promise<T> {
    return instance.get(url, { params })
  },
  post<T>(url: string, data: any): Promise<T> {
    return instance.post(url, data)
  },
  delete<T>(url: string, data: any): Promise<T> {
    return instance.delete(url, data)
  }
}
